import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:岁亮亮
 * Date:2024-06-20
 * TIME:15:39
 */
public class DigHeap {

    private int elem[];
    public int usedSize;
    public DigHeap(){
        this.elem = new int[10];
    }

    public void initArray(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
    }
    public void createDigHeap(){
        for (int parent = (usedSize - 1 -1 ) / 2; parent >= 0; parent--) {
            siftDown(parent,usedSize);
        }

    }

    /***
     * 向下调整创建大根堆
     * 时间复杂度O(N)
     * @param parent
     * @param len
     */
    private void siftDown(int parent, int len) {
        int child = parent*2 + 1;
        while (child < len){
            //进入循环至少说明有一个左孩子 但不能说明有右孩子
            if(child + 1 < len && elem[child] < elem[child+1]){
                child = child +1;
            }
            //执行完上面的if循环后 child下标存储的是左右孩子(若有有孩子的话)的最大值
            if(elem[child] > elem[parent]){
               each(child,parent);
                parent = child;
                child = 2*parent + 1;//这不是递归不要搞混了
            }else {
                break;
            }
        }
    }

    private void each(int child, int parent) {
        int tmp = elem[child];
        elem[child] = elem[parent];
        elem[parent] = tmp;
    }


    //根基层序遍历 创建二叉树
    private void create(int[] array){


    }

    public void push(int target){
        //检查是否满了
        if(isFull()){
            this.elem = Arrays.copyOf(this.elem,elem.length*2);
        }
        this.elem[usedSize] = target;
        //向上调整

        siftUp(usedSize);
        usedSize++;
    }

    private void siftUp( int child) {
        int parent = (usedSize-1)/2;
        while (child > 0){
            if(elem[child] > elem[parent]){
                each(child,parent);
                child = parent;
                parent = (parent - 1)/2;
            }
            else {
                break;
            }
        }
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }


    public int pop(){
        if(isEmpty()){
            return -1;
        }
        int oldElemment = this.elem[0];
        each(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
        return oldElemment;
    }
    public boolean isEmpty(){
        return usedSize == 0;
    }

    /***
      * 堆排序 用大根堆进行从小到大排序
     * 每次把堆顶与堆尾交换再向下调整 确定最大值的位置
     */
    public void heapSort(){
        int end = usedSize-1;
        while (end > 0){
            each(0,end);
            siftDown(0,end);
            end--;
        }
    }


}
